<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Vuex使用方法 | dmf的个人博客</title><meta name="author" content="dmf"><meta name="copyright" content="dmf"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="描述">
<meta property="og:type" content="article">
<meta property="og:title" content="Vuex使用方法">
<meta property="og:url" content="https://gitee.com/dmf-c/blog/2022/01/16/vue_file/vuex/index.html">
<meta property="og:site_name" content="dmf的个人博客">
<meta property="og:description" content="描述">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img1.baidu.com/it/u=1828439677,2166285235&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=300">
<meta property="article:published_time" content="2022-01-15T16:00:00.000Z">
<meta property="article:modified_time" content="2023-01-30T06:03:22.566Z">
<meta property="article:author" content="dmf">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img1.baidu.com/it/u=1828439677,2166285235&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=300"><link rel="shortcut icon" href="/blog/img/favicon.png"><link rel="canonical" href="https://gitee.com/dmf-c/blog/2022/01/16/vue_file/vuex/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/blog/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Vuex使用方法',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-01-30 14:03:22'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">27</div></a><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">0</div></a><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">6</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/blog/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/blog/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://img1.baidu.com/it/u=1828439677,2166285235&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=400&amp;h=300')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blog/">dmf的个人博客</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/blog/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/blog/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Vuex使用方法</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="fa-fw post-meta-icon far fa-calendar-alt"></i><span class="post-meta-label">发表于</span><time datetime="2022-01-15T16:00:00.000Z" title="发表于 2022-01-16 00:00:00">2022-01-16</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/Vue/">Vue</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Vuex使用方法"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>当应用遇到多个组件共享状态时，会需要多个组件依赖于同一状态或者来自不同视图的行为需要变更同一状态。</p>
<p>传参的方法对于多层嵌套的组件会非常繁琐，并且对于兄弟组件间的状态传递无能为力。特别是非父子组件之间通信。此时就应该使用 vuex，轻松可以搞定组件间通信问题。</p>
<h2 id="Vuex-是什么"><a href="#Vuex-是什么" class="headerlink" title="Vuex 是什么"></a>Vuex 是什么</h2><p><strong>vuex 官方解释</strong><br>Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态，并以相应的规则保证状态以一种可预测的方式发生变化。</p>
<p>简单来说,对 vue 应用中多个组件的共享状态进行集中式的管理(读&#x2F;写)。</p>
<h2 id="Vuex-的原理是什么"><a href="#Vuex-的原理是什么" class="headerlink" title="Vuex 的原理是什么"></a>Vuex 的原理是什么</h2><p><strong>1.简要介绍 Vuex 原理</strong></p>
<p>Vuex 实现了一个单向数据流，在全局拥有一个 State 存放数据，当组件要更改 State 中的数据时，必须通过 Mutation 进行，Mutation 同时提供了订阅者模式供外部插件调用获取 State 数据的更新。而当所有异步操作(常见于调用后端接口异步获取更新数据)或批量的同步操作需要走 Action，但 Action 也是无法直接修改 State 的，还是需要通过 Mutation 来修改 State 的数据。最后，根据 State 的变化，渲染到视图上。</p>
<p><strong>2.简要介绍各模块在流程中的主要功能</strong></p>
<p><a target="_blank" rel="noopener" href="https://imgse.com/i/pSdXiFI"><img src="https://s1.ax1x.com/2023/01/30/pSdXiFI.png" alt="pSdXiFI.png"></a></p>
<ul>
<li>Vue Components：Vue 组件。HTML 页面上，负责接收用户操作等交互行为，执行 dispatch 方法触发对应 action 进行回应。</li>
<li>dispatch：操作行为触发方法，是唯一能执行 action 的方法。</li>
<li>actions：<strong>操作行为处理模块,由组件中的$store.dispatch(‘action 名称’, data1)来触发。然后由 commit()来触发 mutation 的调用 , 间接更新 state。</strong> 负责处理 Vue Components 接收到的所有交互行为。包含同步&#x2F;异步操作，支持多个同名方法，按照注册的顺序依次触发。向后台 API 请求的操作就在这个模块中进行，包括触发其他 action 以及提交 mutation 的操作。该模块提供了 Promise 的封装，以支持 action 的链式触发。</li>
<li>commit：状态改变提交操作方法。对 mutation 进行提交，是唯一能执行 mutation 的方法。</li>
<li>mutations：<strong>状态改变操作方法，由 actions 中的 commit(‘mutation 名称’)来触发。</strong> 是 Vuex 修改 state 的唯一推荐方法。该方法只能进行同步操作，且方法名只能全局唯一。操作之中会有一些 hook 暴露出来，以进行 state 的监控等。</li>
<li>state：页面状态管理容器对象。集中存储 Vue components 中 data 对象的零散数据，全局唯一，以进行统一的状态管理。页面显示所需的数据从该对象中进行读取，利用 Vue 的细粒度数据响应机制来进行高效的状态更新。</li>
<li>getters：state 对象读取方法。图中没有单独列出该模块，应该被包含在了 render 中，Vue Components 通过该方法读取全局 state 对象。</li>
</ul>
<h2 id="什么情况使用-Vuex"><a href="#什么情况使用-Vuex" class="headerlink" title="什么情况使用 Vuex"></a>什么情况使用 Vuex</h2><p><strong>在需要构建一个中大型单页应用的需求下，很可能会考虑如何更好地在组件外部管理状态，Vuex 将会成为自然而然的选择。</strong></p>
<h2 id="Vuex-安装-开发环境为-vue-cli"><a href="#Vuex-安装-开发环境为-vue-cli" class="headerlink" title="Vuex 安装(开发环境为 vue-cli)"></a>Vuex 安装(开发环境为 vue-cli)</h2><pre><code>npm config set registry https://[registry.npm.taobao.or(http://registry.npm.taobao.org/)
npm config get registry//配置后可通过下面方式来验证是否成功
npm install -g cnpm --registry=[https://registry](https:registry/).npm.taobao.org
//cnpm安装脚手架
cnpm install -g vue-cli
vue init webpack my-vue
cd my-vue
cnpm install
cnpm run dev
</code></pre>
<p>脚手架安装好后，再安装 vuex</p>
<pre><code>cnpm install vuex --save
</code></pre>
<h2 id="如何使用-Vuex"><a href="#如何使用-Vuex" class="headerlink" title="如何使用 Vuex"></a>如何使用 Vuex</h2><p><strong>1.如何通过 Vue 来实现如下效果？</strong></p>
<p><img src="http://test.imgurl.org/imgs/2023/01/30/19394c6b585ffd0b.gif"></p>
<pre><code>&lt;div class=&quot;hello&quot;&gt;
    &lt;p&gt;click &#123;&#123;count&#125;&#125; times,count is &#123;&#123;evenOrOdd&#125;&#125;&lt;/p&gt;
    &lt;button @click=&quot;increment&quot;&gt;+&lt;/button&gt;
    &lt;button @click=&quot;decrement&quot;&gt;-&lt;/button&gt;
    &lt;button @click=&quot;incrementIfOdd&quot;&gt;increment if odd&lt;/button&gt;
    &lt;button @click=&quot;incrementAsync&quot;&gt;increment async&lt;/button&gt;
&lt;/div&gt;
......
export default &#123;
name: &quot;HelloWorld&quot;,
data() &#123;
    return &#123;
    count: 0
    &#125;;
&#125;,
computed: &#123;
    evenOrOdd() &#123;
    return this.count % 2 === 0 ? &quot;偶数&quot; : &quot;奇数&quot;;
    &#125;
&#125;,
methods: &#123;
    increment() &#123;
    this.count = this.count + 1;
    &#125;,
    decrement() &#123;
    this.count = this.count - 1;
    &#125;,
    // 只有是奇数才加1
    incrementIfOdd() &#123;
    if (this.count % 2 === 1) &#123;
        this.count = this.count + 1;
    &#125;
    &#125;,
    // 过两秒才加1
    incrementAsync() &#123;
    setInterval(() =&gt; &#123;
        this.count = this.count + 1;
    &#125;, 2000);
    &#125;
&#125;
&#125;
</code></pre>
<p><strong>2.如何通过 Vuex 来改造上面代码？</strong></p>
<p><strong>① 创建一个 store.js 文件</strong></p>
<pre><code>import Vue from &#39;vue&#39;
import Vuex from &#39;vuex&#39;
Vue.use(Vuex)
const store = new Vuex.Store(&#123;
    state: &#123;
        count: 0
    &#125;,
    mutations: &#123;// 包含了多个直接更新state函数的对象
        INCREMENT(state) &#123;
            state.count = state.count + 1;
        &#125;,
        DECREMENT(state) &#123;
            state.count = state.count - 1;
        &#125;
    &#125;,
    getters: &#123;   // 当读取属性值时自动调用并返回属性值
        evenOrOdd(state) &#123;
            return state.count % 2 === 0 ? &quot;偶数&quot; : &quot;奇数&quot;;
        &#125;
    &#125;,
    actions: &#123; // 包含了多个对应事件回调函数的对象
        incrementIfOdd(&#123; commit, state &#125;) &#123; // 带条件的action
            if (state.count % 2 === 1) &#123;
                commit(&#39;INCREMENT&#39;)
            &#125;
        &#125;,
        incrementAsync(&#123; commit &#125;) &#123; //异步的action
            setInterval(() =&gt; &#123;
                commit(&#39;INCREMENT&#39;)
            &#125;, 2000);
        &#125;

    &#125;
&#125;)
export default store //用export default 封装代码，让外部可以引用
</code></pre>
<p><strong>② 在 main.js 文件中引入 store.js 文件</strong></p>
<pre><code>import store from &#39;./store&#39;
new Vue(&#123;
el: &#39;#app&#39;,
router,
store,//注册上vuex的store: 所有组件对象都多一个属性$store
components: &#123; App &#125;,
template: &#39;&lt;App/&gt;&#39;
&#125;)
</code></pre>
<p><strong>③ 新建一个模板 HelloWorld.vue</strong></p>
<pre><code>&lt;template&gt;
&lt;div class=&quot;hello&quot;&gt;
    &lt;p&gt;click &#123;&#123;count&#125;&#125; times,count is &#123;&#123;evenOrOdd&#125;&#125;&lt;/p&gt;
    &lt;button @click=&quot;increment&quot;&gt;+&lt;/button&gt;
    &lt;button @click=&quot;decrement&quot;&gt;-&lt;/button&gt;
    &lt;button @click=&quot;incrementIfOdd&quot;&gt;increment if odd&lt;/button&gt;
    &lt;button @click=&quot;incrementAsync&quot;&gt;increment async&lt;/button&gt;
&lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
export default &#123;
name: &quot;HelloWorld&quot;,
computed: &#123;
    count() &#123;
    return this.$store.state.count;
    &#125;,
    evenOrOdd() &#123;
    return this.$store.getters.evenOrOdd;
    &#125;
&#125;,
methods: &#123;
    increment() &#123;
    this.$store.commit(&quot;INCREMENT&quot;);
    &#125;,
    decrement() &#123;
    this.$store.commit(&quot;DECREMENT&quot;);
    &#125;,
    // 只有是奇数才加1
    incrementIfOdd() &#123;
    this.$store.dispatch(&quot;incrementIfOdd&quot;); //触发store中对应的action调用
    &#125;,
    // 过两秒才加1
    incrementAsync() &#123;
    this.$store.dispatch(&quot;incrementAsync&quot;);
    &#125;
&#125;
&#125;;
&lt;/script&gt;
</code></pre>
<p>由于 store 中的状态是响应式的，当 Vue 组件从 store 中读取状态的时候，若 store 中的状态发生变化，那么相应的组件也会相应地得到高效更新。<strong>在组件中调用 store 中的状态简单到仅需要在计算属性中返回即可。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutations。</strong></p>
<p><strong>3.通过 mapState 等辅助函数优化上面代码？</strong></p>
<pre><code>import &#123; mapActions, mapGetters, mapState, mapMutations &#125; from &quot;vuex&quot;;
...
computed: &#123;
    ...mapState([&quot;count&quot;]),
    ...mapGetters([&quot;evenOrOdd&quot;])
    &#125;
methods: &#123;
    ...mapActions([&quot;incrementIfOdd&quot;, &quot;incrementAsync&quot;]),
    ...mapMutations([&quot;increment&quot;, &quot;decrement&quot;])
    &#125;
</code></pre>
<p><strong>注意</strong>：HelloWorld.vue 中 increment 函数名称要跟 store.js 文件 mutations 中一致，才能写成 …mapMutations([“increment”, “decrement”])，同样，incrementIfOdd 和 incrementAsync 也要和 store.js 文件 actions 保持一致。</p>
<h2 id="使用-Vuex-的注意点"><a href="#使用-Vuex-的注意点" class="headerlink" title="使用 Vuex 的注意点"></a>使用 Vuex 的注意点</h2><p><strong>1.如何在 Mutations 里传递参数</strong></p>
<p>先 store.js 文件里给 add 方法加上一个参数 n</p>
<pre><code>mutations: &#123;
  INCREMENT(state,n) &#123;
    state.count+=n;
  &#125;,
  DECREMENT(state)&#123;
      state.count--;
  &#125;
&#125;
</code></pre>
<p>然后在 HelloWorld.vue 里修改按钮的 commit( )方法传递的参数</p>
<pre><code>increment() &#123;
    return this.$store.commit(&quot;INCREMENT&quot;,2);
    &#125;,
decrement() &#123;
    return this.$store.commit(&quot;DECREMENT&quot;);
    &#125;
</code></pre>
<p><strong>2.如何理解 getters</strong></p>
<p><strong>getters 从表面是获得的意思，可以把他看作在获取数据之前进行的一种再编辑,相当于对数据的一个过滤和加工。</strong> getters 就像计算属性一样，getter 的返回值会根据它的依赖被缓存起来，且只有当它的依赖值发生了改变才会被重新计算。</p>
<p>例如：要对 store.js 文件中的 count 进行操作，在它输出前，给它加上 100。</p>
<p>首先要在 store.js 里 Vuex.Store()里引入 getters</p>
<pre><code>getters:&#123;
    count:state=&gt;state.count+=100
&#125;
</code></pre>
<p>然后在 HelloWorld.vue 中对 computed 进行配置，在 vue 的构造器里边只能有一个 computed 属性，如果你写多个，只有最后一个 computed 属性可用，所以要用展开运算符”…”对上节写的 computed 属性进行一个改造。</p>
<pre><code>computed: &#123;
...mapGetters([&quot;count&quot;])
&#125;
</code></pre>
<p><strong>3.actions 和 mutations 区别</strong></p>
<p>actions 和上面的 Mutations 功能基本一样，不同点是，<strong>actions 是异步的改变 state 状态，而 Mutations 是同步改变状态。</strong></p>
<p>尤雨溪:同步的意义在于这样每一个 mutation 执行完成后都可以对应到一个新的状态（和 reducer 一样），这样 devtools 就可以打个 snapshot 存下来，然后就可以随便 time-travel 了。如果你开着 devtool 调用一个异步的 action，你可以清楚地看到它所调用的 mutation 是何时被记录下来的，并且可以立刻查看它们对应的状态。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://gitee.com/dmf-c/blog">dmf</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://gitee.com/dmf-c/blog/2022/01/16/vue_file/vuex/">https://gitee.com/dmf-c/blog/2022/01/16/vue_file/vuex/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://gitee.com/dmf-c/blog" target="_blank">dmf的个人博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://img1.baidu.com/it/u=1828439677,2166285235&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=400&amp;h=300" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blog/2022/01/30/vue_file/vue_router/"><img class="prev-cover" src="https://img1.baidu.com/it/u=1828439677,2166285235&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=400&amp;h=300" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">vue-router学习</div></div></a></div><div class="next-post pull-right"><a href="/blog/2022/01/02/vue_file/assembly/"><img class="next-cover" src="https://img1.baidu.com/it/u=1828439677,2166285235&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=400&amp;h=300" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">vue组件传值的多种方式</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">dmf</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">27</div></a><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">0</div></a><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">6</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">业精于勤，荒于嬉。</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%89%8D%E8%A8%80"><span class="toc-number">1.</span> <span class="toc-text">前言</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Vuex-%E6%98%AF%E4%BB%80%E4%B9%88"><span class="toc-number">2.</span> <span class="toc-text">Vuex 是什么</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Vuex-%E7%9A%84%E5%8E%9F%E7%90%86%E6%98%AF%E4%BB%80%E4%B9%88"><span class="toc-number">3.</span> <span class="toc-text">Vuex 的原理是什么</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%83%85%E5%86%B5%E4%BD%BF%E7%94%A8-Vuex"><span class="toc-number">4.</span> <span class="toc-text">什么情况使用 Vuex</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Vuex-%E5%AE%89%E8%A3%85-%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83%E4%B8%BA-vue-cli"><span class="toc-number">5.</span> <span class="toc-text">Vuex 安装(开发环境为 vue-cli)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8-Vuex"><span class="toc-number">6.</span> <span class="toc-text">如何使用 Vuex</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-Vuex-%E7%9A%84%E6%B3%A8%E6%84%8F%E7%82%B9"><span class="toc-number">7.</span> <span class="toc-text">使用 Vuex 的注意点</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/2023/01/08/vue_file/vuenote/" title="vue3入门笔记"><img src="https://img1.baidu.com/it/u=1828439677,2166285235&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=400&amp;h=300" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="vue3入门笔记"/></a><div class="content"><a class="title" href="/blog/2023/01/08/vue_file/vuenote/" title="vue3入门笔记">vue3入门笔记</a><time datetime="2023-01-07T16:00:00.000Z" title="发表于 2023-01-08 00:00:00">2023-01-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/02/20/vue_file/comm/" title="vue组件间通信六种方式"><img src="https://img1.baidu.com/it/u=1828439677,2166285235&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=400&amp;h=300" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="vue组件间通信六种方式"/></a><div class="content"><a class="title" href="/blog/2022/02/20/vue_file/comm/" title="vue组件间通信六种方式">vue组件间通信六种方式</a><time datetime="2022-02-19T16:00:00.000Z" title="发表于 2022-02-20 00:00:00">2022-02-20</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/02/05/wxEcharts/" title="微信小程序使用 echarts"><img src="https://img1.baidu.com/it/u=1828439677,2166285235&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=400&amp;h=300" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="微信小程序使用 echarts"/></a><div class="content"><a class="title" href="/blog/2022/02/05/wxEcharts/" title="微信小程序使用 echarts">微信小程序使用 echarts</a><time datetime="2022-02-04T16:00:00.000Z" title="发表于 2022-02-05 00:00:00">2022-02-05</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/01/30/vue_file/vue_router/" title="vue-router学习"><img src="https://img1.baidu.com/it/u=1828439677,2166285235&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=400&amp;h=300" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="vue-router学习"/></a><div class="content"><a class="title" href="/blog/2022/01/30/vue_file/vue_router/" title="vue-router学习">vue-router学习</a><time datetime="2022-01-29T16:00:00.000Z" title="发表于 2022-01-30 00:00:00">2022-01-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/01/16/vue_file/vuex/" title="Vuex使用方法"><img src="https://img1.baidu.com/it/u=1828439677,2166285235&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=400&amp;h=300" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="Vuex使用方法"/></a><div class="content"><a class="title" href="/blog/2022/01/16/vue_file/vuex/" title="Vuex使用方法">Vuex使用方法</a><time datetime="2022-01-15T16:00:00.000Z" title="发表于 2022-01-16 00:00:00">2022-01-16</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By dmf</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>